<template>
  <el-dialog :title="addTitle" :visible.sync="addShow" :before-close="close" width="55%">
    <el-form ref="roleAdd" :model="roleAdd" :rules="rules" :inline="true" class="demo-form-inline">
      <el-form-item label="角色名称" prop="name" :label-width="formLabelWidth">
        <el-input v-model="roleAdd.name" autocomplete="off" class="input" />
      </el-form-item>
      <el-form-item label="角色代码" prop="code" :label-width="formLabelWidth">
        <el-input v-model="roleAdd.code" autocomplete="off" class="input" />
      </el-form-item>
      <el-form-item label="角色备注" prop="remark" :label-width="formLabelWidth">
        <el-input v-model="roleAdd.remark" autocomplete="off" class="input" />
      </el-form-item><br>
      <el-form-item label="是否启用" prop="status" :label-width="formLabelWidth">
        <template>
          <el-radio v-model="roleAdd.status" :label="1">是</el-radio>
          <el-radio v-model="roleAdd.status" :label="0">否</el-radio>
        </template>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="add">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'RoleDialog',
  props: {
    addTitle: String, // 表头标题
    addData: Object, // 表单数据
    addShow: Boolean, // 弹窗是否显示
    addClose: Function, // 窗口关闭事件，避免子组件直接修改父组件的参数
    addClick: Function, // 确认事件，传值给父组件
    editClick: Function // 编辑事件
  },
  data() {
    // 工号错误输入
    var name = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('角色名称不能为空'))
      } else {
        callback()
      }
    }
    // 密码错误输入
    var code = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('角色编号不能为空'))
      } else {
        callback()
      }
    }
    return {
      roleAdd: {}, // 初始数据
      rules: {
        name: [
          { required: true, validator: name, trigger: 'blur' }
        ],
        code: [
          { required: true, validator: code, trigger: 'blur' }
        ]
      },
      formLabelWidth: '100px'
    }
  },
  methods: {
    // 初始化
    onshow() {
      this.roleAdd = this.addData // 赋值（来自父组件）
    },
    // 确认按钮
    add() {
      this.$refs.roleAdd.validate((valid) => {
        if (valid) {
          if (this.addTitle === '增加角色' || this.addTitle === '角色复制') {
            this.addClick(this.roleAdd) // 监听addClick传值到父组件添加角色
            this.roleAdd = {}
          } else {
            this.editClick(this.roleAdd)
            // 清空初始值
            this.roleAdd = {}
          }
        } else {
          console.log('输入错误')
          return false
        }
      })
    },
    // 关闭、取消按钮
    close() {
      this.addClose()
      // 清空初始值
      this.roleAdd = {}
      this.$refs.roleAdd.resetFields()
    }
  }
}
</script>

<style>
  .input{
    width:16vw;
  }
</style>
